package servlet;

import bean.Users;
import service.impl.UsersServiceImpl;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(urlPatterns = "/login")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取输入数据
        String username = req.getParameter("username");
        String userpass = req.getParameter("userpass");
        //查询数据库中是否有匹配数据，从而判断能否登录
        UsersServiceImpl usersService = new UsersServiceImpl();
        Users user = usersService.login(username, userpass);
        if (user != null){
            //登录成功，session存值
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            System.out.println("登录成功");
            //跳转到查询页面
            resp.sendRedirect("getUsers.jsp");
        }else {
            resp.sendRedirect("login.jsp");
        }

    }
}
